package cn.edu.dlut.ssdut.foodCredit2012.service;

/*import java.util.List;

import org.hibernate.Query;*/
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.QualityCollection;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class QualityCollectionService {
	
	public void add(QualityCollection q) throws Exception{
		if(!hasQuality(q)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(q);
			session.getTransaction().commit();
		}
	}
	
	public void delete(QualityCollection q) throws Exception{
		if(hasQuality(q)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(q);
			session.getTransaction().commit();
		}
	}
	
	public void update (QualityCollection q) throws Exception{
		if(hasQuality(q)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(q);
			session.getTransaction().commit();
		}
	}
	
	/*public List qualityList() {
		List qualityList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Quality");
		query.setFirstResult(2);
		query.setMaxResults(10);
		qualityList = query.list();
		
		session.getTransaction().commit();
		
		return qualityList;
	}*/
	
	public boolean hasQuality(QualityCollection q) throws Exception {
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from QualityCollection q where q.licenceID = :licenceID")
			.setString("licenceID", q.getLicenceID())
			.uniqueResult();
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public QualityCollection load(QualityCollection q) throws Exception{
		if(hasQuality(q)){
			q = loadByLicenceID(q.getLicenceID());
			return q;
		}
		return q;
	}
	
	public QualityCollection loadByLicenceID(String licenceID) throws Exception{
		QualityCollection q = new QualityCollection();
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		q = (QualityCollection)session.createQuery("select q from QualityCollection q where q.licenceID = :licenceID")
			.setParameter("licenceID", licenceID)
			.uniqueResult();
		session.getTransaction().commit();
		return q;
	}

}
